from app.extensions import db
from app.models.category import Category, CategorySchema

category_schema = CategorySchema()
categories_schema = CategorySchema(many=True)


def get_all_categories():
    return db.session.execute(db.select(Category)).scalars()


def get_category_by_id(category_id):
    return db.get_or_404(Category, category_id)


def add_category(data):
    category = Category(category_name=data['category_name'])
    db.session.add(category)
    db.session.commit()

    return True


def delete_category(category_id):
    existing_category = get_category_by_id(category_id)

    if existing_category:
        db.session.delete(existing_category)
        db.session.commit()

        return True


def update_category(request_data):
    existing_category = get_category_by_id(request_data['category_id'])

    if existing_category:
        existing_category.category_name = request_data['category_name']

        db.session.commit()

        return True
